package com.resafety.clound2020.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.resafety.clound2020.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
@Slf4j
public class orderController {

//    public  static final String URL="http://localhost:8001";
    public  static final String URL="http://CLOUD-PAYMENT-SERVICE";
    @Resource
    private RestTemplate restTemplate;
    //自定义的ribbon负载均衡
    @Resource
    private LoadBalancer loadBalancer;
    //获取当前所有的服务
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/order/create")
    public CommonResult<Payment> create(Payment payment){
        log.info("*******去请求8001");
//        return restTemplate.postForObject(URL+"/payment/create",payment,CommonResult.class);
        return restTemplate.getForObject(URL+"/payment/create",CommonResult.class);
    }
    @GetMapping("/order/create/entity")
    public CommonResult<Payment> createentity(Payment payment){
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(URL+"/payment/create/",CommonResult.class);
        log.info(entity.getStatusCode()+"");
        if(entity.getStatusCode().is2xxSuccessful()){
            return entity.getBody();
        }else{
            return new CommonResult(444,"操作失败");
        }
    }
    //自定义负载均衡
    @GetMapping("/order/create/lb")
    public String lb(){
        System.out.println(11111);
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");//根据微服务名称获取up
        if(instances == null || instances.size() <= 0){
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
//        System.out.println(serviceInstance.getServiceId());
        String posturl=uri+"/payment/lb";

       return restTemplate.getForObject(posturl,String.class);
    }
}
